const userDao = require('../dao/userDao');
const md5 = require('../utils/md/md5');

async function addUser(user) {
    user.password = md5.hexMD5(user.password);
    var data = await userDao.findByName(user);
    if (data.success) {
        return {
            success: false,
            msg: 'the user is existed already!'
        }
    } else {
        var result = await userDao.createUser(user);
        return result;
    }
}

async function login(user) {
    var result = await userDao.findByName(user);
    // console.log(result);
    // 判断是否存在该用户
    if (result.success) {
        // 判断用户密码是否正确
        user.password = md5.hexMD5(user.password);
        // console.log(user.name, user.password, result.user.password, user.password == result.user.password);
        if (user.password == result.user.password) {
            return {
                success: true,
                user: result.user    //在dao层返回的user
            }
        } else {
            return {
                success: false,
                msg: 'please check your password ^_^'
            }
        }
    } else {
        return result;
    }
}

async function loginCookie(user) {
    var result = await userDao.findByName(user);
    // 判断是否存在该用户
    if (result.success) {
        // console.log(user.name, user.password, result.user.password, user.password == result.user.password);
        if (user.password == result.user.password) {
            return {
                success: true,
                user: result.user
            }
        } else {
            return {
                success: false,
                msg: 'please check your password ^_^'
            }
        }
    } else {
        return result;
    }
}

module.exports = {
    addUser: addUser,
    login: login,
    loginCookie: loginCookie
}